#!/bin/sh
##############################################################################
#  OpenDomo: Security & Domotics
#  Copyright (C) 2008  Isidro Catalan <skarvin@gmail.com>
#
#  This program is free software: you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation, either version 3 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program.  If not, see <http://www.gnu.org/licenses/>.
##############################################################################
# ----------------------------------------------------------------------------
# desc: Primera aproximacion del script de gestion de alertas de Opendomo
# author: Isidro Catalan <skarvin@gmail.com>, http://www.opendomo.com
# date: October 2008
#
# CHANGES:
#
# ----------------------------------------------------------------------------

# Lib config
. "$OD_COMMON_MODULE/scripts/libConfig.sh"

EMAIL="/usr/local/bin/email"
SMTP="smtp.gmail.com"
PORT="587"
SENDER="skarvin@gmail.com"
# set the config file for video alert options
CONF_FILE="/etc/opendomo/contact.conf"
SSL="1"
HTML="1"
EMAIL_PARAMS=""
AUTH="login"
# reading main settings
email=`getValue "email" | sed 's/\"//g'`
sms=`getValue "sms" | sed 's/\"//g'`
# possible values notice|warning|error
level="$1"
alert_type="$2"
module="$3"
msg="$4"
att="$5"

# Sends an E-Mail
sendEmail ()
{
	if [ -z "$email" ]; then
		echo "# Ninguna direccion de E-Mail configurada!"
	fi
	# building params
	if [ "$SSL" = "1" ]; then
		EMAIL_PARAMS="$EMAIL_PARAMS -tls"
	fi
	if [ "$HTML" = "1" ]; then
		EMAIL_PARAMS="$EMAIL_PARAMS -html"
	fi
	if [ "$AUTH" = "login" ]; then
		EMAIL_PARAMS="$EMAIL_PARAMS -i$MY_PWD"
	fi	
	if [ ! -z "$att" ]; then
		EMAIL_PARAMS="$EMAIL_PARAMS -a$att"
	fi
	
	subject="[OpenDomo Alertas] - Alerta generada por el módulo [$module]"
	mail_body="
		$msg<br />
		Alerta de tipo [$level]<br />
	"
	echo $mail_body | $EMAIL -u $SENDER -m$AUTH -r $SMTP -p $PORT -s"$subject" $EMAIL_PARAMS $email 2> /tmp/errors > /tmp/errors

}

# Sends an SMS
sendSMS ()
{
	echo "# Not working yet"
}

# switch the alert type
case "$alert_type" in
	E-mail)
		sendEmail;;
	SMS)
		sendSMS;;
	all)
		sendEmail
		sleep 1
		sendSMS;;
	*)
	echo "# Opción no reconocida!"
esac
